<template>
    <div class="dining-service">
        <el-tabs v-model="activeTab">
            <!-- 菜谱浏览 -->
            <el-tab-pane label="菜谱浏览" name="menu">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-input
                            v-model="menuSearch"
                            placeholder="搜索菜品名称"
                            prefix-icon="el-icon-search"
                            clearable
                            @input="filterMenus"
                            style="margin-bottom: 20px;"
                        />
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="menu in filteredMenus" :key="menu.id">
                        <el-card class="menu-card" shadow="hover">
                            <template #header>
                                <div class="menu-header">
                                    <span>{{ menu.name }}</span>
                                    <el-tag size="small">{{ menu.category }}</el-tag>
                                </div>
                            </template>
                            <div class="menu-content">
                                <div class="menu-price">¥{{ menu.price.toFixed(2) }}</div>
                                <div class="menu-description">{{ menu.description || '暂无描述' }}</div>
                                <el-button 
                                    type="primary" 
                                    size="small" 
                                    plain 
                                    @click="addToOrder(menu)"
                                    style="margin-top: 10px;"
                                >
                                    加入预约
                                </el-button>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
                <el-empty v-if="filteredMenus.length === 0" description="暂无菜品数据" />
            </el-tab-pane>

            <!-- 餐饮预约 -->
            <el-tab-pane label="餐饮预约" name="order">
                <el-form :model="orderForm" ref="orderFormRef" label-width="100px" class="order-form">
                    <el-form-item label="服务类型">
                        <el-select v-model="orderForm.typeSId" placeholder="请选择服务类型">
                            <el-option
                                v-for="type in serviceTypes"
                                :key="type.id"
                                :label="type.serviceName"
                                :value="type.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="预约日期">
                        <el-date-picker
                            v-model="orderForm.reserveDate"
                            type="date"
                            placeholder="选择日期"
                            :disabled-date="disabledDate"
                        />
                    </el-form-item>
                    <el-form-item label="服务地点">
                        <el-input v-model="orderForm.serviceAddress" placeholder="请输入服务地点"/>
                    </el-form-item>
                    <el-form-item label="订单详情">
                        <div v-if="selectedMenus.length > 0" class="selected-menus">
                            <div v-for="(item, index) in selectedMenus" :key="index" class="selected-menu-item">
                                <div class="menu-item-info">
                                    <span class="menu-item-name">{{ item.name }}</span>
                                    <span class="menu-item-price">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
                                </div>
                                <div class="menu-item-actions">
                                    <el-input-number 
                                        v-model="item.quantity" 
                                        :min="1" 
                                        :max="10"
                                        size="small"
                                        @change="updateOrderDetail"
                                    />
                                    <el-button 
                                        type="danger" 
                                        size="small" 
                                        icon="el-icon-delete" 
                                        circle
                                        @click="removeSelectedMenu(index)"
                                    />
                                </div>
                            </div>
                            <div class="total-price">总价: ¥{{ calculateTotalPrice() }}</div>
                        </div>
                        <div v-else class="no-menu-selected">
                            <el-empty description="暂未选择任何菜品" :image-size="100">
                                <el-button @click="activeTab = 'menu'" type="primary">去选择菜品</el-button>
                            </el-empty>
                        </div>
                        <el-input v-model="orderForm.orderDetail" type="hidden" />
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input
                            type="textarea"
                            v-model="orderForm.remark"
                            :rows="3"
                            placeholder="请输入备注信息"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitOrder">提交预约</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>

            <!-- 需求反馈 -->
            <el-tab-pane label="需求反馈" name="feedback">
                <dining-feedback />
            </el-tab-pane>

            <!-- 我的订单 -->
            <el-tab-pane label="我的订单" name="myOrders">
                <div class="orders-header">
                    <h3>我的预约订单</h3>
                    <el-button type="primary" size="small" @click="getMyOrders" :loading="loading">
                        <i class="el-icon-refresh"></i> 刷新列表
                    </el-button>
                </div>
                
                <el-table :data="myOrders" v-loading="loading" border @row-click="showOrderDetail">
                    <el-table-column label="下单日期" width="120">
                        <template #default="scope">
                            <span>{{ formatOrderDate(scope.row.orderDate) || '未知' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="预约日期" width="120">
                        <template #default="scope">
                            <span>{{ formatOrderDate(scope.row.reserveDate) || '未知' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="服务地点" width="120">
                        <template #default="scope">
                            <span>{{ scope.row.serviceAddress || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="订单详情">
                        <template #default="scope">
                            <span>{{ scope.row.orderDetail || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" width="100">
                        <template #default="scope">
                            <span>{{ scope.row.remark || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" width="100">
                        <template #default="scope">
                            <el-tag :type="getOrderStateType(scope.row.orderState)">
                                {{ getOrderStateText(scope.row.orderState) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template #default="scope">
                            <div class="order-actions">
                                <el-button
                                    v-if="scope.row.orderState === 3"
                                    type="primary"
                                    size="small"
                                    @click.stop="showReviewDialog(scope.row)"
                                >
                                    评价
                                </el-button>
                                <el-button
                                    type="info"
                                    size="small"
                                    icon="el-icon-view"
                                    circle
                                    @click.stop="showOrderDetail(scope.row)"
                                ></el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                
                <el-empty v-if="myOrders.length === 0" description="暂无订单数据" />
                
                <!-- 调试信息 -->
                <div v-if="myOrders.length > 0 && isDev" class="debug-info">
                    <p>订单数据结构预览：</p>
                    <pre>{{ JSON.stringify(myOrders[0], null, 2) }}</pre>
                </div>
            </el-tab-pane>
        </el-tabs>

        <!-- 评价对话框 -->
        <service-order-review ref="reviewDialog" @review-submitted="getMyOrders"/>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '../../../utils/axios'
import { useUserStore } from '../../../stores/user'
import DiningFeedback from '../../serve/dining/DiningFeedback.vue'
import ServiceOrderReview from '../../serve/serviceOrder/ServiceOrderReview.vue'

const userStore = useUserStore()
const activeTab = ref('order')
const loading = ref(false)
const reviewDialog = ref(null)

// 判断是否为开发环境
const isDev = process.env.NODE_ENV === 'development'

// 获取当前用户ID
const getCurrentUserId = () => {
    try {
        const userStr = localStorage.getItem('user')
        if (!userStr) {
            console.warn('未找到用户信息')
            return null
        }
        const user = JSON.parse(userStr)
        if (!user || !user.id) {
            console.warn('用户信息不完整:', user)
            return null
        }
        return user.id
    } catch (error) {
        console.error('获取用户信息失败:', error)
        return null
    }
}

// 表单数据
const orderForm = ref({
    userId: getCurrentUserId(),
    typeSId: null,
    reserveDate: null,
    serviceAddress: '',
    orderDetail: '',
    remark: ''
})

// 服务类型列表
const serviceTypes = ref([])

// 我的订单列表
const myOrders = ref([])

// 菜谱列表
const menuList = ref([])
const filteredMenus = ref([])
const menuSearch = ref('')
const selectedMenus = ref([])

// 向控制台打印网络请求详情
const logApiResponse = async (url, method = 'GET') => {
  if (!isDev) return;
  
  console.log(`%c🔍 检查API: ${method} ${url}`, 'color: blue; font-weight: bold');
  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 5000);
    
    const response = await fetch(url, {
      method,
      signal: controller.signal,
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    clearTimeout(timeoutId);
    
    console.log(`%c📡 响应状态: ${response.status} ${response.statusText}`, 'color: purple');
    
    const contentType = response.headers.get('content-type');
    if (contentType && contentType.includes('application/json')) {
      const data = await response.json();
      console.log('%c📦 响应数据:', 'color: green', data);
    } else {
      console.log('%c⚠️ 非JSON响应:', 'color: orange', await response.text());
    }
  } catch (error) {
    console.error('%c❌ 请求失败:', 'color: red', error);
  }
};

// 获取服务类型
const getServiceTypes = async () => {
    try {
        // 先获取餐饮服务大类
        const typeBResponse = await axios.get('/serviceType/selectFather1')
        if (!typeBResponse.data || typeBResponse.data.code !== 200) {
            throw new Error('获取服务大类失败')
        }
        
        console.log('获取到的服务大类:', typeBResponse.data.result)
        const diningType = typeBResponse.data.result.find(type => 
            type.serviceName.includes('餐饮') || type.serviceName.includes('送餐')
        )
        if (!diningType) {
            throw new Error('未找到餐饮服务类型')
        }
        
        console.log('找到的餐饮服务类型:', diningType)
        
        // 获取餐饮服务子类
        const response = await axios.get(`/serviceType/selectChildren1ByFather/${diningType.id}`)
        if (response.data && response.data.code === 200) {
            serviceTypes.value = response.data.result || []
            console.log('获取到的餐饮服务子类:', serviceTypes.value)
            if (serviceTypes.value.length === 0) {
                ElMessage.warning('暂无可用的餐饮服务类型')
            }
        } else {
            throw new Error(response.data.message || '获取服务子类失败')
        }
    } catch (error) {
        console.error('获取服务类型失败:', error)
        ElMessage.error('获取服务类型失败：' + (error.message || '未知错误'))
        serviceTypes.value = []
    }
}

// 获取我的订单
const getMyOrders = async () => {
    const userId = getCurrentUserId()
    if (!userId) {
        ElMessage.warning('请先登录后再查看订单')
        return
    }
    
    loading.value = true
    const apiUrl = `/serviceOrder/selectByUId/${userId}`;
    
    // 如果是开发环境，额外检查API
    if (isDev) {
      // 使用新的函数检查API
      logApiResponse(axios.defaults.baseURL + apiUrl);
    }
    
    // 保存当前订单数据，防止刷新时清空
    const existingOrders = [...myOrders.value];
    console.log('保存现有订单数据:', existingOrders);
    
    try {
        console.log('正在获取订单数据，用户ID:', userId)
        const response = await axios.get(apiUrl)
        console.log('获取订单响应:', response.data)
        
        if (response.data.code === 200) {
            // 检查结果是否为数组
            let orders = response.data.result || []
            
            // 如果返回的不是数组，尝试解析
            if (!Array.isArray(orders)) {
                console.warn('后端返回的不是数组:', orders)
                
                if (typeof orders === 'object') {
                    // 可能是分页对象
                    if (orders.records && Array.isArray(orders.records)) {
                        orders = orders.records
                        console.log('从分页对象中提取数据:', orders)
                    } else {
                        // 如果是单个对象，放入数组
                        orders = [orders]
                        console.log('将单个对象放入数组:', orders)
                    }
                } else {
                    orders = []
                    console.warn('无法解析的数据类型，设为空数组')
                }
            }
            
            // 处理订单数据，确保所有字段都存在
            const processedOrders = orders.map(order => {
                console.log('处理订单数据:', order)
                // 确保所有必要字段都有默认值
                return {
                    // 设置默认值，防止数据缺失导致显示问题
                    id: order.id || 0,
                    orderDate: order.orderDate || null,
                    reserveDate: order.reserveDate || null,
                    serviceAddress: order.serviceAddress || '',
                    orderDetail: order.orderDetail || '',
                    remark: order.remark || '',
                    orderState: typeof order.orderState === 'number' ? order.orderState : 0,
                    ...order  // 保留其他原始字段
                }
            });
            
            if (processedOrders.length > 0) {
                console.log('使用服务器返回的订单数据:', processedOrders)
                myOrders.value = processedOrders;
            } else {
                console.log('服务器返回的订单数据为空，检查是否有本地添加的订单')
                // 如果存在本地添加且没有被覆盖的订单，保留它们
                if (existingOrders.length > 0) {
                    console.log('保留本地添加的订单:', existingOrders)
                    myOrders.value = existingOrders;
                    return true;
                }
                myOrders.value = [];
            }
            
            console.log('处理后的订单数据:', myOrders.value)
            return true;
        } else if (response.data.code === 404) {
            console.log('后端返回404，暂无订单数据')
            // 如果存在本地添加的订单，保留它们
            if (existingOrders.length > 0) {
                console.log('服务器返回404，但保留本地添加的订单:', existingOrders)
                myOrders.value = existingOrders;
                return true;
            }
            
            myOrders.value = []
            ElMessage.info('暂无订单数据')
            return false;
        } else {
            console.warn('后端返回错误码:', response.data.code, response.data.message)
            // 如果存在本地添加的订单，保留它们
            if (existingOrders.length > 0) {
                console.log('服务器返回错误，但保留本地添加的订单:', existingOrders)
                myOrders.value = existingOrders;
                return true;
            }
            
            myOrders.value = []
            throw new Error(response.data.message || '获取订单列表失败')
        }
    } catch (error) {
        console.error('获取订单列表失败:', error)
        
        // 如果存在本地添加的订单，保留它们
        if (existingOrders.length > 0) {
            console.log('获取订单失败，但保留本地添加的订单:', existingOrders)
            myOrders.value = existingOrders;
            return true;
        }
        
        myOrders.value = []
        
        // 检查错误类型
        if (error.response) {
            console.error('响应状态码:', error.response.status)
            console.error('响应数据:', error.response.data)
            
            if (error.response.status === 404) {
                console.log('服务器返回404，暂无订单数据')
                ElMessage.info('暂无订单数据')
            } else {
                ElMessage.error('获取订单列表失败：' + (error.response.data?.message || '服务器错误'))
            }
        } else if (error.request) {
            console.error('请求已发送但没有收到响应')
            ElMessage.error('服务器无响应，请稍后再试')
        } else {
            console.error('请求设置出错:', error.message)
            ElMessage.error('获取订单列表失败：' + error.message)
        }
        return false;
    } finally {
        loading.value = false
    }
}

// 获取菜谱列表
const getMenuList = async () => {
    try {
        const response = await axios.get('/dining/menu/list', {
            params: {
                pageNum: 1,
                pageSize: 50
            }
        })
        
        if (response.data && response.data.code === 200) {
            menuList.value = response.data.result.records || []
            filteredMenus.value = [...menuList.value]
            console.log('获取到的菜谱列表:', menuList.value)
        } else {
            throw new Error(response.data.message || '获取菜谱列表失败')
        }
    } catch (error) {
        console.error('获取菜谱列表失败:', error)
        ElMessage.error('获取菜谱列表失败：' + (error.message || '未知错误'))
        menuList.value = []
        filteredMenus.value = []
    }
}

// 过滤菜谱
const filterMenus = () => {
    if (!menuSearch.value) {
        filteredMenus.value = [...menuList.value]
        return
    }
    
    const searchTerm = menuSearch.value.toLowerCase()
    filteredMenus.value = menuList.value.filter(menu => 
        menu.name.toLowerCase().includes(searchTerm) || 
        (menu.description && menu.description.toLowerCase().includes(searchTerm)) ||
        (menu.category && menu.category.toLowerCase().includes(searchTerm))
    )
}

// 添加到预约
const addToOrder = (menu) => {
    if (activeTab.value !== 'menu') {
        return
    }
    
    const userId = getCurrentUserId()
    if (!userId) {
        ElMessage.warning('请先登录后再加入预约')
        return
    }
    
    // 检查是否已经添加过该菜品
    const existingIndex = selectedMenus.value.findIndex(item => item.id === menu.id)
    
    if (existingIndex >= 0) {
        // 如果已经添加过，增加数量
        selectedMenus.value[existingIndex].quantity += 1
        ElMessage.success(`已增加 ${menu.name} 的数量`)
    } else {
        // 如果是新菜品，添加到列表
        selectedMenus.value.push({
            ...menu,
            quantity: 1
        })
        ElMessage.success(`已将 ${menu.name} 加入预约`)
    }
    
    // 更新订单详情，将所有选中菜品转换为字符串
    updateOrderDetail()
    
    // 自动切换到预约标签
    activeTab.value = 'order'
}

// 移除已选菜品
const removeSelectedMenu = (index) => {
    selectedMenus.value.splice(index, 1)
    updateOrderDetail()
}

// 更新订单详情
const updateOrderDetail = () => {
    if (selectedMenus.value.length === 0) {
        orderForm.value.orderDetail = ''
        return
    }
    
    orderForm.value.orderDetail = selectedMenus.value.map(item => 
        `${item.name} x ${item.quantity}(¥${(item.price * item.quantity).toFixed(2)})`
    ).join('，')
}

// 计算总价
const calculateTotalPrice = () => {
    return selectedMenus.value.reduce((total, item) => total + (item.price * item.quantity), 0).toFixed(2)
}

// 提交预约
const submitOrder = async () => {
    const userId = getCurrentUserId()
    if (!userId) {
        ElMessage.warning('请先登录后再提交预约')
        return
    }

    if (!orderForm.value.typeSId) {
        ElMessage.warning('请选择服务类型')
        return
    }
    
    if (!orderForm.value.reserveDate) {
        ElMessage.warning('请选择预约日期')
        return
    }
    
    if (!orderForm.value.serviceAddress) {
        ElMessage.warning('请填写服务地点')
        return
    }
    
    if (selectedMenus.value.length === 0) {
        ElMessage.warning('请选择至少一个菜品')
        return
    }

    try {
        console.log("开始提交预约，用户ID:", userId)
        // 先获取餐饮服务大类ID
        const typeBResponse = await axios.get('/serviceType/selectFather1')
        console.log('获取到的服务大类:', typeBResponse.data)
        
        if (!typeBResponse.data || typeBResponse.data.code !== 200) {
            throw new Error('获取服务大类失败')
        }
        
        // 尝试不同的关键词查找餐饮服务
        let diningType = typeBResponse.data.result.find(type => 
            type.serviceName.includes('餐饮') || 
            type.serviceName.includes('送餐') || 
            type.serviceName.includes('用餐') ||
            type.serviceName.includes('饮食')
        )
        
        console.log('找到的餐饮服务类型:', diningType)
        
        if (!diningType) {
            // 如果找不到特定的餐饮类型，使用第一个服务类型
            console.warn('未找到餐饮服务类型，将使用第一个服务类型')
            if (typeBResponse.data.result.length === 0) {
                throw new Error('没有可用的服务类型')
            }
            diningType = typeBResponse.data.result[0]
        }

        // 构建订单数据
        updateOrderDetail()  // 确保订单详情已更新
        
        // 添加价格信息到订单详情
        const totalPrice = calculateTotalPrice()
        let enhancedOrderDetail = orderForm.value.orderDetail
        if (!enhancedOrderDetail.includes('总价')) {
            enhancedOrderDetail += `，总价:¥${totalPrice}`
        }

        // 确保日期格式正确
        const formattedDate = orderForm.value.reserveDate instanceof Date 
            ? orderForm.value.reserveDate.toISOString().split('T')[0]
            : orderForm.value.reserveDate;

        // 获取用户信息
        const userInfo = userStore.userInfo || {}
        console.log('当前用户信息:', userInfo)

        // 获取当前时间用于显示
        const now = new Date();
        const currentDate = now.toISOString().split('T')[0];
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const currentTime = `${hours}:${minutes}`;

        // 构建请求数据结构
        const orderData = {
            uId: parseInt(userId),
            typeBId: diningType.id,
            typeSId: parseInt(orderForm.value.typeSId),
            reserveDate: formattedDate,
            serviceAddress: orderForm.value.serviceAddress,
            orderDetail: enhancedOrderDetail,
            remark: orderForm.value.remark || '',
            orderState: 0,
            name: userInfo.name || '',
            telephone: userInfo.telephone || ''
        }
        
        console.log('提交订单数据:', orderData)
        
        const response = await axios.put('/serviceOrder/insert', orderData)
        console.log('订单提交响应:', response.data)
        
        if (response.data.code === 200) {
            ElMessage.success('预约提交成功')
            
            // 检查响应中是否有订单ID
            let newOrderId = null
            if (response.data.result && response.data.result.id) {
                newOrderId = response.data.result.id
                console.log('新订单ID:', newOrderId)
            } else if (response.data.result && typeof response.data.result === 'number') {
                // 有些API可能直接返回ID作为result
                newOrderId = response.data.result
                console.log('新订单ID(数字):', newOrderId)
            }
            
            // 重置表单
            orderForm.value = {
                userId: getCurrentUserId(),
                typeSId: null,
                reserveDate: null,
                serviceAddress: '',
                orderDetail: '',
                remark: ''
            }
            
            // 清空已选菜品
            selectedMenus.value = []
            
            // 先切换到我的订单选项卡
            activeTab.value = 'myOrders'
            
            // 创建临时订单对象，无论是否有ID都添加（使用随机ID）
            const tempId = newOrderId || Math.floor(Math.random() * -1000000) // 使用负数ID避免与真实ID冲突
            
            // 创建带有完整字段的订单对象
            const newOrder = {
                id: tempId,
                uId: parseInt(userId),
                typeBId: diningType.id,
                typeSId: parseInt(orderForm.value.typeSId),
                reserveDate: formattedDate,  // 使用表单中的预约日期
                orderDate: currentDate,      // 使用当前日期作为下单日期
                orderTime: currentTime,      // 使用当前时间作为下单时间
                serviceAddress: orderData.serviceAddress,
                orderDetail: orderData.orderDetail,
                remark: orderData.remark,
                orderState: 0, // 待受理
                name: userInfo.name || '',
                telephone: userInfo.telephone || '',
                // 添加服务类型名称
                typeB: { serviceName: diningType.serviceName || '餐饮服务' },
                typeS: { 
                    serviceName: serviceTypes.value.find(t => t.id === parseInt(orderData.typeSId))?.serviceName || '送餐服务' 
                },
                // 添加用户信息
                user: {
                    id: parseInt(userId),
                    name: userInfo.name || '',
                    telephone: userInfo.telephone || ''
                },
                manager: null  // 未分配工作人员
            }
            
            // 将新订单添加到列表顶部
            myOrders.value.unshift(newOrder)
            console.log('添加新订单到列表:', newOrder)
            
            // 使用保持现有订单的方式获取更新
            setTimeout(async () => {
                console.log('开始刷新订单列表')
                try {
                    // 直接从服务器获取最新的订单数据
                    const success = await getMyOrdersDirectly(userId)
                    console.log('刷新订单列表完成，状态:', success ? '成功' : '失败')
                } catch (err) {
                    console.error('刷新订单列表失败:', err)
                    // 如果刷新失败，已添加的订单依然会保留在列表中
                } finally {
                    loading.value = false
                }
            }, 1000)
        } else {
            throw new Error(response.data.message || '预约提交失败')
        }
    } catch (error) {
        console.error('提交预约失败:', error)
        ElMessage.error('提交预约失败：' + (error.response?.data?.message || error.message || '未知错误'))
    }
}

// 直接从服务器获取订单数据（跳过缓存）
const getMyOrdersDirectly = async (userId) => {
    if (!userId) {
        userId = getCurrentUserId()
        if (!userId) {
            console.warn('未找到用户ID，无法获取订单')
            return false
        }
    }
    
    console.log('直接从服务器获取订单，用户ID:', userId)
    
    // 保存当前订单数据，防止刷新时清空
    const existingOrders = [...myOrders.value];
    console.log('保存现有订单数据:', existingOrders);
    
    try {
        // 添加时间戳防止缓存
        const timestamp = new Date().getTime()
        const response = await axios.get(`/serviceOrder/selectByUId/${userId}?_t=${timestamp}`)
        console.log('获取订单响应:', response.data)
        
        if (response.data.code === 200) {
            // 检查结果是否为数组
            let orders = response.data.result || []
            
            // 如果返回的不是数组，尝试解析
            if (!Array.isArray(orders)) {
                console.warn('后端返回的不是数组:', orders)
                
                if (typeof orders === 'object') {
                    // 可能是分页对象
                    if (orders.records && Array.isArray(orders.records)) {
                        orders = orders.records
                        console.log('从分页对象中提取数据:', orders)
                    } else {
                        // 如果是单个对象，放入数组
                        orders = [orders]
                        console.log('将单个对象放入数组:', orders)
                    }
                } else {
                    orders = []
                    console.warn('无法解析的数据类型，设为空数组')
                }
            }
            
            // 处理订单数据，确保所有字段都存在
            const processedOrders = orders.map(order => {
                console.log('处理订单数据:', order)
                // 确保所有必要字段都有默认值
                return {
                    // 设置默认值，防止数据缺失导致显示问题
                    id: order.id || 0,
                    orderDate: order.orderDate || null,
                    reserveDate: order.reserveDate || null,
                    serviceAddress: order.serviceAddress || '',
                    orderDetail: order.orderDetail || '',
                    remark: order.remark || '',
                    orderState: typeof order.orderState === 'number' ? order.orderState : 0,
                    ...order  // 保留其他原始字段
                }
            });
            
            if (processedOrders.length > 0) {
                console.log('使用服务器返回的订单数据:', processedOrders)
                myOrders.value = processedOrders;
            } else {
                console.log('服务器返回的订单数据为空，检查是否有本地添加的订单')
                // 如果存在本地添加且没有被覆盖的订单，保留它们
                if (existingOrders.length > 0) {
                    console.log('保留本地添加的订单:', existingOrders)
                    myOrders.value = existingOrders;
                    return true;
                }
                myOrders.value = [];
            }
            
            console.log('直接获取的订单数据:', myOrders.value)
            return true
        } else {
            // 如果存在本地添加的订单，保留它们
            if (existingOrders.length > 0) {
                console.log('服务器返回错误，但保留本地添加的订单:', existingOrders)
                myOrders.value = existingOrders;
                return true;
            }
            
            console.warn('获取订单失败:', response.data.message)
            return false
        }
    } catch (error) {
        console.error('直接获取订单失败:', error)
        
        // 如果存在本地添加的订单，保留它们
        if (existingOrders.length > 0) {
            console.log('获取订单失败，但保留本地添加的订单:', existingOrders)
            myOrders.value = existingOrders;
            return true;
        }
        
        return false
    }
}

// 显示评价对话框
const showReviewDialog = (order) => {
    const userId = getCurrentUserId()
    if (!userId) {
        ElMessage.warning('请先登录')
        return
    }
    reviewDialog.value.showReviewDialog(order.id, userId)
}

// 禁用今天之前的日期
const disabledDate = (time) => {
    return time.getTime() < Date.now() - 8.64e7
}

// 获取订单状态类型
const getOrderStateType = (state) => {
    if (state === null || state === undefined) return 'info';
    
    switch (parseInt(state)) {
        case 0: return 'info';     // 待受理 - 蓝色
        case 1: return 'danger';   // 已取消 - 红色
        case 2: return 'warning';  // 待完成 - 黄色
        case 3: return 'primary';  // 待评价 - 紫色
        case 4: return 'success';  // 已完成 - 绿色
        default: return 'info';
    }
}

// 获取订单状态文本
const getOrderStateText = (state) => {
    if (state === null || state === undefined) return '待受理';
    
    switch (parseInt(state)) {
        case 0: return '待受理';
        case 1: return '已取消';
        case 2: return '待完成';
        case 3: return '待评价';
        case 4: return '已完成';
        default: return '未知状态';
    }
}

// 格式化订单日期
const formatOrderDate = (dateStr) => {
    if (!dateStr) return '-';
    
    try {
        // 如果是字符串，尝试解析
        if (typeof dateStr === 'string') {
            // 处理不同格式的日期字符串
            if (dateStr.includes('T')) {
                // ISO格式: 2023-01-01T00:00:00
                const date = new Date(dateStr);
                if (!isNaN(date.getTime())) {
                    return date.toISOString().split('T')[0];
                }
            } else if (dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) {
                // 已经是YYYY-MM-DD格式
                return dateStr;
            }
        }
        // 其他情况返回原始值
        return dateStr;
    } catch (error) {
        console.error('日期格式化错误:', error);
        return dateStr || '-';
    }
};

// 显示订单详情
const showOrderDetail = (row) => {
    if (!row || !row.id) {
        ElMessage.warning('订单数据不完整')
        return
    }
    
    console.log('查看订单详情:', row)
    
    // 格式化日期显示
    const formatDate = (dateStr) => {
        if (!dateStr) return '未知日期'
        try {
            const date = new Date(dateStr)
            if (isNaN(date.getTime())) return dateStr
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
        } catch (error) {
            return dateStr
        }
    }
    
    // 构建详情内容
    const content = `
        <div class="order-detail-dialog">
            <div class="detail-item"><span class="label">订单ID:</span> ${row.id}</div>
            <div class="detail-item"><span class="label">下单日期:</span> ${formatDate(row.orderDate)}</div>
            <div class="detail-item"><span class="label">预约日期:</span> ${formatDate(row.reserveDate)}</div>
            <div class="detail-item"><span class="label">服务地点:</span> ${row.serviceAddress || '-'}</div>
            <div class="detail-item"><span class="label">订单详情:</span> ${row.orderDetail || '-'}</div>
            <div class="detail-item"><span class="label">备注:</span> ${row.remark || '-'}</div>
            <div class="detail-item"><span class="label">订单状态:</span> ${getOrderStateText(row.orderState)}</div>
        </div>
    `
    
    ElMessageBox.alert(content, '订单详情', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭'
    })
}

// 在组件挂载时初始化数据
onMounted(async () => {
    try {
        await getServiceTypes()
        await getMyOrders()
        await getMenuList()  // 获取菜谱列表
    } catch (error) {
        console.error('初始化数据失败:', error)
    }
})
</script>

<style scoped>
.dining-service {
    padding: 20px;
}

.order-form {
    max-width: 600px;
    margin: 0 auto;
}

.el-table {
    margin-top: 20px;
}

.menu-card {
    margin-bottom: 20px;
}

.menu-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.menu-content {
    text-align: center;
}

.menu-price {
    font-size: 1.2rem;
    color: #f56c6c;
    font-weight: bold;
    margin: 10px 0;
}

.menu-description {
    font-size: 0.9rem;
    color: #666;
    margin-bottom: 10px;
    height: 40px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.selected-menus {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 10px;
    margin-bottom: 10px;
    min-height: 60px;
}

.selected-menu-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px dashed #ebeef5;
}

.menu-item-info {
    flex: 1;
    display: flex;
    justify-content: space-between;
    margin-right: 15px;
}

.menu-item-name {
    font-weight: bold;
}

.menu-item-price {
    color: #f56c6c;
}

.menu-item-actions {
    display: flex;
    align-items: center;
    gap: 10px;
}

.no-menu-selected {
    margin: 10px 0;
}

.total-price {
    margin-top: 10px;
    font-weight: bold;
    text-align: right;
    color: #f56c6c;
    font-size: 16px;
}

.orders-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.orders-header h3 {
    margin: 0;
}

.debug-info {
    margin-top: 20px;
    padding: 10px;
    background-color: #f9f9f9;
    border: 1px solid #eee;
    border-radius: 4px;
}

.debug-info pre {
    white-space: pre-wrap;
    word-break: break-all;
    font-size: 12px;
    line-height: 1.4;
}

.order-actions {
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.order-detail-dialog .detail-item {
    margin-bottom: 10px;
    line-height: 1.5;
}

.order-detail-dialog .label {
    font-weight: bold;
    color: #606266;
    margin-right: 10px;
}
</style> 